package com.baibei.ebec.user.register;

import android.Manifest;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baibei.basic.IPresenter;
import com.baibei.ebec.user.R;
import com.baibei.ebec.user.R2;
import com.baibei.module.AppRouter;
import com.baibei.module.BasicActivity;
import com.baibei.ui.AppUI;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 注册企业用户
 * Created by ChenRui on 2017/8/2 0002 17:34.
 */
@Route(path = AppRouter.ROUTER_USER_REGISTER_ENTERPRISE)
public class RegisterEnterpriseActivity extends BasicActivity implements RegisterEnterpriseContract.View {

    private static final int REQ_IMAGE = 1023;

    @BindView(R2.id.img_license)
    ImageView mLicenseImage;

    @BindView(R2.id.btn_register)
    Button mRegButton;

    @BindView(R2.id.et_name)
    EditText mNameText;
    @BindView(R2.id.et_id_card)
    EditText mIdCardText;
    private Uri mUri;
    private RegisterEnterpriseContract.Presenter mPresenter;
    private TextWatcher mTextWatch;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_enterprise);
        mPresenter = inject(RegisterEnterpriseContract.Presenter.class);
        mTextWatch = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                validateForm();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        };
        TextViewCompat.registerFormListener(mTextWatch, mNameText, mIdCardText);

        List<InputFilter> filterList = new ArrayList<>();
        filterList.addAll(Arrays.asList(mIdCardText.getFilters()));
        filterList.add(new InputFilter() {

            Pattern mPattern = Pattern.compile("[a-zA-z0-9]");

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                // 删除等特殊字符，直接返回
                if ("".equals(source.toString())) {
                    return null;
                }
                String dValue = source.toString();

                if (!mPattern.matcher(dValue).find()) {
                    return "";
                }
                return null;
            }
        });

        InputFilter[] filters = new InputFilter[filterList.size()];
        mIdCardText.setFilters(filterList.toArray(filters));
    }

    @Override
    protected void onDestroy() {
        TextViewCompat.unregisterFormListener(mTextWatch, mNameText, mIdCardText);
        super.onDestroy();
    }

    private void requestPermission() {
        // 申请权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
            }, 10089);
        }
    }

    private void validateForm() {
        if (mNameText.length() > 1 && mIdCardText.length() >= 15 && mUri != null) {
            mRegButton.setEnabled(true);
        } else {
            mRegButton.setEnabled(false);
        }
    }

    @Override
    public IPresenter getBasicPresenter() {
        return mPresenter;
    }


    @OnClick({R2.id.img_license, R2.id.btn_license})
    public void onImageLicenseClick() {
        onButtonLicenseClick();
        mLicenseImage.setVisibility(View.GONE);
    }

    @OnClick(R2.id.ll_license)
    public void onButtonLicenseClick() {
        try {
            requestPermission();

            // 弹出文件选择对话框
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent, REQ_IMAGE);
            mUri = null;
        } catch (Exception e) {
            e.printStackTrace();
            AppUI.failed(this, "没有权限访问系统相册");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 10089) {
            if (grantResults.length < 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                AppUI.failed(this, "请授权访问才能继续下一步操作");
            }
        }
    }

    public String getImageUriFilePath(final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = getContentResolver().query(uri,
                    new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    @OnClick(R2.id.btn_register)
    public void onRegClick() {
        AppUI.loading(this, "正在注册..").setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                mPresenter.cancel();
            }
        });
        mPresenter.register();
    }

    @Override
    public String getMobile() {
        return getIntent().getStringExtra("mobile");
    }

    @Override
    public String getPassword() {
        return getIntent().getStringExtra("password");
    }

    @Override
    public String getSmsCode() {
        return getIntent().getStringExtra("smsCode");
    }

    @Override
    public String getLegalPersonName() {
        return mNameText.getText().toString();
    }

    @Override
    public String getLegalPersonCertNo() {
        return mIdCardText.getText().toString();
    }

    @Override
    public String getBizLicencePicture() {
        return getImageUriFilePath(mUri);
    }

    @Override
    public void onRegisterSuccess() {

        // 跳转到审核界面
        AppUI.dismiss();
        AppRouter.routeToRegisterSuccessStatus(this);
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void onRegisterFailed(String msg) {
        AppUI.dismiss();
        AppUI.failed(this, msg);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQ_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
            mUri = data.getData();
            mLicenseImage.setImageURI(mUri);
            mLicenseImage.setVisibility(View.VISIBLE);
            validateForm();
            return;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}
